package com.yuan.yblog.portal.asyn;


import com.yuan.yblog.common.consts.Constants;
import com.yuan.yblog.common.utils.*;
import com.yuan.yblog.crud.entity.LoginRecords;
import com.yuan.yblog.crud.entity.OperationLog;
import com.yuan.yblog.crud.mapper.OperationLogMapper;
import com.yuan.yblog.crud.service.ILoginRecordsService;
import com.yuan.yblog.portal.listener.CanalListener;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 */
@Slf4j
public class AsyncFactory
{

    /**
     * 记录登录信息
     * @param username 用户名
     * @param status 状态
     * @param message 消息
     * @param args 列表
     * @return 任务task
     */
    public static TimerTask recordLoginInfo(final String username,
                                            final String status,
                                            final String message,
                                            final Object... args)
    {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr();
        return new TimerTask()
        {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(getBlock(ip));
                s.append(address);
                s.append(getBlock(username));
                s.append(getBlock(status));
                s.append(getBlock(message));
                // 打印信息到日志
                log.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                LoginRecords logininfor = new LoginRecords();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                // 日志状态
                if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
                {
                    logininfor.setStatus(Constants.SUCCESS);
                }
                else if (Constants.LOGIN_FAIL.equals(status))
                {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 登录时间
                logininfor.setLoginTime(new Date());
                // 插入数据
                SpringUtils.getBean(ILoginRecordsService.class).save(logininfor);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operationLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOperationLog(final OperationLog operationLog)
    {
        return new TimerTask()
        {
            @Override
            public void run() {
                // 远程查询操作地点
                operationLog.setOperLocation(AddressUtils.getRealAddressByIP(operationLog.getOperIp()));
                //插入数据库
                SpringUtils.getBean(OperationLogMapper.class).insert(operationLog);

            }
        };
    }

    /**
     * 处理并记录日志文件
     */
    private static String getBlock(Object msg)
    {
        if (msg == null)
        {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }

    /**
     *  启动canal监听
     */
    public static TimerTask canalListen()
    {
        return new TimerTask()
        {
            @Override
            public void run() {
                try {
                    SpringUtils.getBean(CanalListener.class).canalListen();
                } catch (Exception e) {
                    throw new RuntimeException("canal监听线程终止：" + e.getMessage());
                }
            }
        };
    }

}
